<template>
  <div class="data-auth-col">
    <p>数据权限 - 列权限</p>
    <div class="col-wrap">
      <div class="company-list">
        <h6>选择公司和部门</h6>
        <el-tree
          :data="treeList"
          :props="defaultProps"
          accordion
          highlight-current
          empty-text="暂无内容"
          @node-click="handleNodeClick"
          @node-expand="handleNodeClick"
        ></el-tree>
      </div>
      <div class="col-content">
        <div class="content-wrap" v-loading="loading">
          <div class="title">已选权限数据</div>
          <div class="content-handler">
            <span class="item" :class="{ select: way === 2 }" @click="selectWay(2)">标签包</span>
            <span class="item" :class="{ select: way === 3 }" @click="selectWay(3)">标签</span>
            <el-input v-model="keyword" placeholder="输入搜索关键字" @keyup.native.enter="search">
              <i class="el-icon-close" slot="suffix" @click="clearSearch" v-if="keyword.length"></i>
              <el-button slot="append" @click="search"><icon-svg name="iconSearch"></icon-svg></el-button>
            </el-input>
          </div>
          <div class="content-list">
            <template v-if="way === 2">
              <div v-if="!packages.dataList.length && !loading" class="no-records">
                <img src="~@/assets/img/no_records.png" alt="" /><br />
                暂无内容
              </div>
              <template v-else>
                <ul class="list-box tag-scrollbar">
                  <li
                    v-for="item in packages.dataList"
                    :key="item.packetId"
                    class="list-item"
                    :class="{ 'active-item': editing }"
                  >
                    {{ item.packetNm }}
                    <div class="item-mount">
                      <el-tooltip effect="dark" content="批量挂载" placement="top">
                        <el-button size="mini" plain circle v-if="editing" @click="handleMount(item)">
                          <icon-svg name="iconAuthMount"></icon-svg>
                        </el-button>
                      </el-tooltip>
                    </div>
                    <span class="item-info" v-if="!showBtn(item)">已选择</span>
                    <el-button
                      icon="el-icon-arrow-right"
                      size="mini"
                      class="item-handler"
                      plain
                      circle
                      @click="addItem(item)"
                      v-if="editing && showBtn(item)"
                    ></el-button>
                  </li>
                </ul>
                <el-pagination
                  @current-change="handlePackageCurrentChange"
                  :current-page="packages.params.currentPageNum"
                  :page-size="packages.params.pageSize"
                  :pager-count="5"
                  background
                  layout="total, prev, pager, next"
                  small
                  :total="packages.totalSize"
                >
                </el-pagination>
              </template>
            </template>
            <template v-else>
              <div v-if="!tag.dataList.length && !loading" class="no-records">
                <img src="~@/assets/img/no_records.png" alt="" /><br />
                暂无内容
              </div>
              <template v-else>
                <ul class="list-box tag-scrollbar">
                  <li
                    v-for="item in tag.dataList"
                    :key="item.assetId"
                    class="list-item"
                    :class="{ 'active-item': editing }"
                  >
                    {{ item.assetNm }}
                    <div class="item-mount">
                      <el-tooltip effect="dark" content="批量挂载" placement="top">
                        <el-button size="mini" plain circle v-if="editing" @click="handleMount(item)">
                          <icon-svg name="iconAuthMount"></icon-svg>
                        </el-button>
                      </el-tooltip>
                    </div>
                    <span class="item-info" v-if="!showBtn(item)">已选择</span>
                    <el-button
                      icon="el-icon-arrow-right"
                      size="mini"
                      class="item-handler"
                      plain
                      circle
                      @click="addItem(item)"
                      v-if="editing && showBtn(item)"
                    ></el-button>
                  </li>
                </ul>
                <el-pagination
                  @current-change="handleTagCurrentChange"
                  :current-page="tag.params.currentPageNum"
                  :page-size="tag.params.pageSize"
                  :pager-count="5"
                  background
                  layout="total, prev, pager, next"
                  small
                  :total="tag.totalSize"
                >
                </el-pagination>
              </template>
            </template>
          </div>
          <div class="content-info"><i class="el-icon-d-arrow-right"></i></div>
          <div class="content-list tag-scrollbar">
            <ul v-if="selectedList.length">
              <li
                v-for="(item, index) in selectedList"
                :key="item.authValue"
                class="list-item"
                :class="{ 'active-item': editing }"
              >
                {{ item.authValueDesc }}
                <el-button
                  icon="el-icon-close"
                  size="mini"
                  class="item-handler delete-btn"
                  plain
                  circle
                  @click="deleteItem(index)"
                  v-if="editing"
                ></el-button>
              </li>
            </ul>
            <div v-else class="no-records">
              <img src="~@/assets/img/no_records.png" alt="" /><br />
              暂无内容
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-row>
      <el-col align="right">
        <el-button type="primary" v-if="!editing" @click="editing = true">修改</el-button>
        <template v-else>
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="submit(false)">保存</el-button>
          <el-button type="primary" @click="submit(true)">保存并退出</el-button>
        </template>
      </el-col>
    </el-row>
    <auth-dialog ref="authDialog" @callback="refresh"></auth-dialog>
  </div>
</template>

<script>
import authDialog from './auth-col-dialog'
export default {
  components: { authDialog },
  data() {
    return {
      editing: false,
      treeList: [],
      defaultProps: {
        label: 'deptFname',
        children: '_children'
      },
      selectDept: -1,
      way: 2,
      loading: false,
      selectedList: [],
      packages: {
        dataList: [],
        params: {
          ascs: [],
          descs: [],
          currentPageNum: 1,
          pageSize: 10,
          queryParams: {},
          descPriority: false
        },
        totalSize: 0
      },
      tag: {
        dataList: [],
        params: {
          ascs: [],
          descs: [],
          currentPageNum: 1,
          pageSize: 10,
          queryParams: {},
          descPriority: false
        },
        totalSize: 0
      },
      keyword: ''
    }
  },
  methods: {
    getParams() {
      this.getCompanys()
      this.getPackageList()
    },
    getCompanys() {
      this.treeList = []
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagDerivedAuth/col/comp'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          data.data.forEach(item =>
            this.treeList.push({
              deptFname: item.compFname,
              _children: [{ deptFname: '' }],
              deptId: item.compId,
              treeLevel: -1
            })
          )
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    handleNodeClick(node) {
      if (node.treeLevel == -1) {
        // 点击公司层级，获取部门列表
        this.getDepts(node)
      } else {
        // 点击部门层级，获取标签列表
        if (this.selectDept === node.deptId) return
        this.selectDept = node.deptId
        this.resetParams()
        this.getSelectedAsset()
      }
    },
    getDepts(node) {
      this.$ajax({
        url: this.$ajax.setUrl(`ast/astTagDerivedAuth/col/dept/${node.deptId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          let list = this.$utils.arrayToTree(data.data, {
            id: 'deptId',
            pid: 'parentDeptId',
            mainSort: 'treeLevel'
          })
          const index = this.treeList.findIndex(item => item.deptId === node.deptId)
          this.treeList[index]._children = list
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getPackageList() {
      this.loading = true
      this.packages.params.queryParams.packetNm = this.keyword
      this.$ajax({
        url: this.$ajax.setUrl(`ast/astTagDerivedAuth/col/packet`),
        method: 'get',
        params: this.$ajax.setParams(this.packages.params)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.packages.dataList = data.data.records
          this.packages.totalSize = data.data.totalSize
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    getTagList() {
      this.loading = true
      this.tag.params.queryParams.assetNm = this.keyword
      this.$ajax({
        url: this.$ajax.setUrl(`ast/astTagDerivedAuth/col/tag`),
        method: 'get',
        params: this.$ajax.setParams(this.tag.params)
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.tag.dataList = data.data.records
          this.tag.totalSize = data.data.totalSize
        } else {
          this.$message.error(data.data || data.msg)
        }
        this.loading = false
      })
    },
    getSelectedAsset() {
      this.$ajax({
        url: this.$ajax.setUrl(`ast/astTagDerivedAuth/col/list/${this.selectDept}/${this.way}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.selectedList = data.data || []
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    handlePackageCurrentChange(val) {
      this.packages.params.currentPageNum = val
      this.getPackageList()
    },
    handleTagCurrentChange(val) {
      this.tag.params.currentPageNum = val
      this.getTagList()
    },
    resetParams() {
      this.packages.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
      this.tag.params = {
        ascs: [],
        descs: [],
        currentPageNum: 1,
        pageSize: 10,
        queryParams: {},
        descPriority: false
      }
    },
    selectWay(way) {
      if (this.way === way) return
      this.way = way
      this.keyword = ''
      if (this.way === 2) this.getPackageList()
      else this.getTagList()
      this.getSelectedAsset()
    },
    addItem(item) {
      if (this.selectDept < 0) {
        this.$message.info('先选择部门！')
        return
      }
      if (this.way === 2) {
        if (!this.selectedList.find(packet => packet.authValue == item.packetId))
          this.selectedList.push({ authValue: item.packetId, authValueDesc: item.packetNm })
      } else {
        if (!this.selectedList.find(tag => tag.authValue == item.assetId))
          this.selectedList.push({ authValue: item.assetId, authValueDesc: item.assetNm })
      }
    },
    deleteItem(index) {
      this.selectedList.splice(index, 1)
    },
    handleMount(item) {
      this.$refs.authDialog.showDialog({
        authType: this.way,
        authValue: item.assetId || item.packetId,
        authNm: item.assetNm || item.packetNm
      })
    },
    refresh(way) {
      this.selectWay(way)
      if (way === 2) this.getPackageList()
      else this.getTagList()
      this.getSelectedAsset()
    },
    submit(cancel = false) {
      if (this.selectDept < 0) {
        this.$message.info('先选择部门和数据！')
        return
      }
      let params = {
        authKey: this.selectDept,
        authKeyDesc: '',
        authType: this.way,
        authValue: '',
        authValueList: this.selectedList
      }
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagDerivedAuth/col'),
        method: 'post',
        data: this.$ajax.setData([params], false, 'json')
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.$message.success(data.msg)
          if (cancel) this.editing = false
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    showBtn(item) {
      if (this.editing) {
        if (this.way === 2) {
          if (this.selectedList.find(select => select.authValue == item.packetId)) {
            return false
          } else {
            return true
          }
        } else {
          if (this.selectedList.find(select => select.authValue == item.assetId)) {
            return false
          } else {
            return true
          }
        }
      } else {
        return true
      }
    },
    cancelEdit() {
      this.editing = false
      this.getSelectedAsset()
    },
    search() {
      this.resetParams()
      if (this.way === 2) this.getPackageList()
      else this.getTagList()
    },
    clearSearch() {
      this.keyword = ''
      this.search()
    }
  }
}
</script>

<style lang="scss">
$bg-color: #4d81ea;
.data-auth-col {
  .col-wrap {
    height: 450px;
    padding-top: 40px;
    margin-bottom: 20px;
    display: flex;
  }
  .company-list {
    width: 400px;
    margin-right: 50px;
    h6 {
      font-size: 14px;
      font-weight: normal;
      text-align: center;
      margin-top: -25px;
    }
    .el-tree {
      margin-top: 10px;
    }
    .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
      color: #fff;
      background-color: $bg-color;
    }
  }
  .col-content {
    flex: 1;
  }
  .content-wrap {
    height: 100%;
    border: 1px solid #eee;
    position: relative;
  }
  .title {
    font-size: 14px;
    width: 45%;
    text-align: center;
    position: absolute;
    left: 55%;
    top: -30px;
  }
  .content-handler {
    width: 45%;
    position: absolute;
    top: -40px;
    left: -1px;
    .item {
      display: inline-block;
      width: 100px;
      height: 40px;
      text-align: center;
      line-height: 40px;
      padding: 0 20px;
      border: 1px solid #eee;
      border-bottom-color: #fff;
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      background-color: #e4efff;
      cursor: pointer;
      &.select {
        color: #fff;
        background-color: $bg-color;
        border-bottom-color: #eee;
      }
    }
    .el-input {
      width: calc(100% - 250px);
      margin-left: 50px;
      .el-input__suffix {
        top: 12px;
      }
      .el-input-group__append {
        color: #fff;
        background-color: $bg-color;
        border-color: $bg-color;
      }
    }
  }
  .content-list {
    float: left;
    width: 45%;
    height: 100%;
    padding-top: 10px;
    border: 1px solid #ddd;
    overflow-y: auto;
  }
  .content-info {
    float: left;
    width: 10%;
    text-align: center;
    i {
      color: $theme-color;
      font-size: 30px;
      margin-top: 175px;
    }
  }
  .list-box {
    height: calc(100% - 30px);
    overflow-y: auto;
  }
  .el-pagination {
    text-align: right;
  }
  .list-item {
    line-height: 40px;
    padding: 0 90px 0 20px;
    position: relative;
    &.active-item:hover {
      color: #fff;
      background-color: $bg-color;
      .delete-btn {
        display: block;
      }
      .item-info {
        color: #fff;
      }
    }
  }
  .item-mount {
    position: absolute;
    top: 0;
    right: 60px;
    .el-button {
      width: 26px;
      height: 26px;
    }
  }
  .item-handler {
    width: 25px;
    height: 25px;
    padding: 5px;
    position: absolute;
    top: 7.5px;
    right: 15px;
  }
  .item-info {
    width: 50px;
    height: 40px;
    line-height: 40px;
    position: absolute;
    right: 0;
    color: $bg-color;
  }
  .disable-btn {
    color: #aaa !important;
    border-color: #aaa !important;
  }
  .delete-btn {
    display: none;
  }
  .no-records {
    text-align: center;
    img {
      margin: 20px 0;
    }
  }
}
</style>
